<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>酒店列表</span>
        <div class="search-container">
          <el-input v-model="searchName" placeholder="输入酒店名称搜索" clearable @clear="resetSearch" style="width: 250px;">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="searchHotel">搜索</el-button>
            </template>
          </el-input>
        </div>
        <!-- 移除管理员的新增酒店按钮，因为管理员有专门的酒店管理页面 -->
      </div>
    </template>
    
    <!-- 优化筛选区域 -->
    <div class="filter-section">
      <div class="filter-content">
        <div class="filter-item">
          <span class="filter-label">地区筛选：</span>
          <el-select v-model="regionFilter" placeholder="选择地区" clearable @change="applyFilters" style="width: 180px;">
            <el-option
              v-for="region in availableRegions"
              :key="region"
              :label="region"
              :value="region"
            />
          </el-select>
        </div>
        
        <div class="filter-item">
          <span class="filter-label">评分筛选：</span>
          <el-select v-model="ratingFilter" placeholder="选择评分" clearable @change="applyFilters" style="width: 180px;">
            <el-option label="5星及以上" :value="5" />
            <el-option label="4星及以上" :value="4" />
            <el-option label="3星及以上" :value="3" />
            <el-option label="2星及以上" :value="2" />
            <el-option label="1星及以上" :value="1" />
          </el-select>
        </div>
        
        <div class="filter-actions">
          <el-button type="primary" @click="resetFilters">重置筛选</el-button>
        </div>
      </div>
      
      <div v-if="activeSearch || activeFilters.length > 0" class="active-filters">
        <div class="filter-tags">
          <el-tag closable @close="resetSearch" v-if="activeSearch">
            搜索: {{ activeSearch }}
          </el-tag>
          <el-tag 
            v-for="filter in activeFilters" 
            :key="filter.type" 
            closable 
            @close="removeFilter(filter.type)"
            type="success"
            class="filter-tag"
          >
            {{ filter.label }}
          </el-tag>
        </div>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="filteredTableData.length === 0" class="empty-container">
      <el-empty description="暂无酒店数据" />
    </div>
    
    <el-row :gutter="20" v-else>
      <el-col :span="24" v-for="hotel in filteredTableData" :key="hotel.hotelName" class="hotel-card-col">
        <el-card class="hotel-card" shadow="hover">
          <div class="hotel-layout">
            <div class="hotel-image">
              <img :src="hotel.image || '/src/assets/default.png'" alt="酒店图片">
            </div>
            <div class="hotel-info">
              <h3 class="hotel-name">{{ hotel.hotelName }}</h3>
              <div class="hotel-location">
                <el-icon><Location /></el-icon>
                <span>{{ hotel.country }} {{ hotel.city }}</span>
              </div>
              <div class="hotel-rating">
                <el-rate v-model="hotel.rating" disabled show-score text-color="#ff9900" />
              </div>
              
              <!-- 最新评论展示 -->
              <div class="hotel-latest-review" v-if="hotel.latestReview">
                <div class="review-title">最新评论:</div>
                <div class="review-content">
                  <el-tooltip :content="hotel.latestReview.content" placement="top" :show-after="200">
                    <div class="review-text">{{ truncateText(hotel.latestReview.content, 100) }}</div>
                  </el-tooltip>
                  <div class="review-meta">
                    <span>{{ formatDate(hotel.latestReview.reviewTime) }}</span>
                    <el-rate v-model="hotel.latestReview.rating" disabled show-score size="small" />
                  </div>
                </div>
              </div>
              <div class="hotel-latest-review" v-else>
                <div class="review-title">暂无评论</div>
              </div>
              
              <div class="hotel-actions">
                <el-button type="primary" @click.stop="viewHotelDetail(hotel)">查看酒店详情</el-button>
                <el-button type="primary" @click.stop="viewHotelRooms(hotel)">查看房间</el-button>
                
                <!-- 移除管理员的编辑和删除按钮，因为管理员有专门的酒店管理页面 -->
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <div class="pagination-box">
      <el-pagination background layout="total, sizes, prev, pager, next"
                     v-model:current-page="pageIndex"
                     v-model:page-size="pageSize"
                     :page-sizes="[12, 24, 36, 48]"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :total="total"/>
    </div>
    
    <!-- 移除管理员的创建和更新酒店组件，因为管理员有专门的酒店管理页面 -->
  </el-card>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getHotelList } from '@/api/hotel'
import { getReviewsByHotel } from '@/api/review'
import { Location, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/stores/userInfo'

const router = useRouter()
const route = useRoute()
const userInfoStore = useUserInfoStore()
const tableData = ref([])
const total = ref(0)
const pageIndex = ref(1)
const pageSize = ref(12) // 调整为适合卡片布局的数量
const loading = ref(true)
const searchName = ref('')
const activeSearch = ref('')

// 筛选相关
const regionFilter = ref('')
const ratingFilter = ref<number | ''>('') // 修改为联合类型，可以是数字或空字符串
const availableRegions = ref([])
const activeFilters = ref([])

// 筛选后的数据
const filteredTableData = computed(() => {
  // 如果没有筛选条件，直接返回原始数据
  if (!regionFilter.value && !ratingFilter.value) {
    return tableData.value
  }
  
  return tableData.value.filter(hotel => {
    // 地区筛选
    const passRegionFilter = !regionFilter.value || 
      (hotel.city && hotel.city === regionFilter.value) || 
      (hotel.country && hotel.country === regionFilter.value)
      
    // 评分筛选
    const passRatingFilter = !ratingFilter.value || 
      (hotel.rating && Number(hotel.rating) >= Number(ratingFilter.value))
    
    // 同时满足两个条件
    return passRegionFilter && passRatingFilter
  })
})

// 按酒店名称搜索
const fetchHotelsByName = async (name) => {
  if (!name) return
  
  console.log('开始按名称搜索酒店:', name);
  loading.value = true
  
  try {
    // 获取所有酒店，然后在前端筛选
    const res = await getHotelList({ pageIndex: 1, pageSize: 1000 })
    const result = res.data;
    
    if (result && result.code === 200) {
      // 前端进行模糊搜索（不区分大小写）
      const searchTerm = name.toLowerCase();
      const filteredData = Array.isArray(result.data) 
        ? result.data.filter(hotel => 
            hotel.hotelName.toLowerCase().includes(searchTerm) ||
            (hotel.city && hotel.city.toLowerCase().includes(searchTerm)) ||
            (hotel.country && hotel.country.toLowerCase().includes(searchTerm))
          )
        : [];
      
      tableData.value = filteredData;
      total.value = filteredData.length;
      
      // 提取可用地区
      extractAvailableRegions();
      
      // 获取每个酒店的最新评论
      await fetchHotelsLatestReviews();
      
      // 恢复URL中保存的筛选条件
      restoreFiltersFromUrl();
      
      if (filteredData.length === 0) {
        ElMessage.info('没有找到匹配的酒店');
      }
    } else {
      console.error('获取酒店列表失败:', result);
      ElMessage.error(result?.msg || '获取酒店列表失败');
    }
  } catch (error) {
    console.error('获取酒店列表错误:', error);
    ElMessage.error('网络错误，获取酒店列表失败');
  } finally {
    loading.value = false;
  }
}

// 应用筛选条件
const applyFilters = () => {
  // 更新活动筛选标签
  activeFilters.value = []
  
  if (regionFilter.value) {
    activeFilters.value.push({
      type: 'region',
      label: `地区: ${regionFilter.value}`
    })
  }
  
  if (ratingFilter.value) {
    activeFilters.value.push({
      type: 'rating',
      label: `评分: ${ratingFilter.value}星及以上`
    })
  }
  
  // 更新URL参数
  router.push({
    path: '/hotel',
    query: {
      ...route.query,
      ...(regionFilter.value ? { region: regionFilter.value } : {}),
      ...(ratingFilter.value ? { rating: ratingFilter.value } : {})
    }
  })
}

// 移除特定筛选条件
const removeFilter = (filterType) => {
  if (filterType === 'region') {
    regionFilter.value = ''
  } else if (filterType === 'rating') {
    ratingFilter.value = ''
  }
  
  // 重新应用筛选
  applyFilters()
}

// 重置所有筛选条件
const resetFilters = () => {
  regionFilter.value = ''
  ratingFilter.value = ''
  activeFilters.value = []
  
  // 清除URL中的筛选参数
  const query = { ...route.query }
  delete query.region
  delete query.rating
  router.push({ query })
}

// 提取可用地区
const extractAvailableRegions = () => {
  const regions = new Set()
  
  tableData.value.forEach(hotel => {
    // 添加城市
    if (hotel.city) {
      regions.add(hotel.city)
    }
    
    // 添加国家
    if (hotel.country) {
      regions.add(hotel.country)
    }
  })
  
  availableRegions.value = Array.from(regions)
}

// 初始化数据，获取所有酒店列表
const fetchAllHotels = async () => {
  console.log('开始请求所有酒店列表数据...');
  loading.value = true
  
  try {
    const res = await getHotelList({ pageIndex: pageIndex.value, pageSize: pageSize.value })
    const result = res.data;
    
    if (result && result.code === 200) {
      tableData.value = Array.isArray(result.data) ? result.data : [];
      total.value = tableData.value.length;
      
      // 提取可用地区
      extractAvailableRegions()
      
      // 获取每个酒店的最新评论
      await fetchHotelsLatestReviews();
      
      // 恢复URL中保存的筛选条件
      restoreFiltersFromUrl()
    } else {
      console.error('获取酒店列表失败:', result);
      ElMessage.error(result?.msg || '获取酒店列表失败');
    }
  } catch (error) {
    console.error('获取酒店列表错误:', error);
    ElMessage.error('网络错误，获取酒店列表失败');
  } finally {
    loading.value = false;
  }
}

// 从URL恢复筛选条件
const restoreFiltersFromUrl = () => {
  const { region, rating } = route.query
  
  if (region) {
    regionFilter.value = region as string
  }
  
  if (rating) {
    ratingFilter.value = parseInt(rating as string, 10)
  }
  
  // 如果有筛选条件，应用它们
  if (region || rating) {
    applyFilters()
  }
}

// 获取每个酒店的最新评论
const fetchHotelsLatestReviews = async () => {
  // 为每个酒店获取最新评论
  for (const hotel of tableData.value) {
    try {
      const res = await getReviewsByHotel(hotel.hotelName);
      const result = res.data as any;
      
      let reviews = [];
      if (Array.isArray(result)) {
        reviews = result;
      } else if (result && (result.code === 200 || result.code === 0) && Array.isArray(result.data)) {
        reviews = result.data;
      }
      
      // 按时间排序，获取最新的评论
      if (reviews.length > 0) {
        reviews.sort((a, b) => new Date(b.reviewTime).getTime() - new Date(a.reviewTime).getTime());
        hotel.latestReview = reviews[0];
      }
    } catch (error) {
      console.error(`获取酒店 ${hotel.hotelName} 的评论失败:`, error);
    }
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleDateString();
}

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text) return '';
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
}

// 处理酒店响应数据
const processHotelResponse = (res) => {
  console.log('获取酒店列表响应:', res);
  
  const result = res.data;
  console.log('后端返回的原始数据结构:', result);
  
  if (result && result.code === 200) {
    tableData.value = Array.isArray(result.data) ? result.data : [];
    total.value = tableData.value.length;
    
    console.log('处理后的酒店数据:', tableData.value);
    
    if (tableData.value.length > 0) {
      console.log('第一条酒店数据的字段名:', Object.keys(tableData.value[0]));
    } else {
      console.log('酒店列表为空');
    }
  } else {
    console.error('获取酒店列表失败:', result);
    ElMessage.error(result?.msg || '获取酒店列表失败');
  }
  
  loading.value = false
}

// 处理错误
const handleError = (error) => {
  console.error('获取酒店列表错误:', error);
  ElMessage.error('网络错误，获取酒店列表失败');
  loading.value = false
}

// 初始化数据
const initData = () => {
  // 如果URL有搜索参数，优先处理
  if (route.query.searchName) {
    searchName.value = route.query.searchName as string
    activeSearch.value = searchName.value
    fetchHotelsByName(searchName.value)
  } else {
    fetchAllHotels()
  }
}

// 搜索酒店
const searchHotel = () => {
  if (!searchName.value) {
    resetSearch()
    return
  }
  
  activeSearch.value = searchName.value
  
  // 更新URL参数
  router.push({
    path: '/hotel',
    query: { ...route.query, searchName: searchName.value }
  })
  
  fetchHotelsByName(searchName.value)
}

// 重置搜索
const resetSearch = () => {
  searchName.value = ''
  activeSearch.value = ''
  
  // 清除URL参数
  const query = { ...route.query }
  delete query.searchName
  router.push({ query })
  
  fetchAllHotels()
}

// 监听URL参数变化
watch(() => route.query.searchName, (newVal) => {
  if (newVal) {
    searchName.value = newVal as string
    activeSearch.value = newVal as string
    fetchHotelsByName(newVal as string)
  } else {
    // 如果URL参数被清除，恢复显示所有酒店
    if (activeSearch.value) {
      resetSearch()
    }
  }
}, { immediate: true })

const handleSizeChange = (size: number) => {
  pageSize.value = size
  initData()
}
const handleCurrentChange = (index: number) => {
  pageIndex.value = index
  initData()
}

// 查看酒店房间
const viewHotelRooms = (hotel: any) => {
  // 可以选择跳转到特定酒店的房间列表页面
  router.push({
    path: '/rooms',
    query: { hotelName: hotel.hotelName }
  })
}

// 查看酒店评价
const viewHotelReviews = (hotel: any) => {
  // 可以实现跳转到该酒店的评价列表页面
  router.push({
    path: '/review',
    query: { hotelName: hotel.hotelName }
  })
}

// 查看酒店详情
const viewHotelDetail = (hotel: any) => {
  router.push({
    path: `/hotel/${encodeURIComponent(hotel.hotelName)}/detail`
  });
}

onMounted(() => {
  initData()
})
</script>
<style scoped>
.page-container {
  min-height: calc(100vh - 120px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  flex: 1;
  display: flex;
  justify-content: center;
  margin: 0 20px;
}

.filter-section {
  margin-bottom: 25px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

.filter-content {
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
  white-space: nowrap;
}

.filter-actions {
  margin-left: auto;
}

.active-filters {
  padding: 0 20px 15px;
  border-top: 1px solid #ebeef5;
  margin-top: 5px;
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding-top: 15px;
}

.filter-tag {
  margin-right: 5px;
}

.loading-container, .empty-container {
  padding: 40px;
  text-align: center;
}

.hotel-card-col {
  margin-bottom: 20px;
}

.hotel-card {
  width: 100%;
  cursor: pointer;
  transition: transform 0.3s;
}

.hotel-card:hover {
  transform: translateY(-5px);
}

.hotel-layout {
  display: flex;
  gap: 20px;
}

.hotel-image {
  width: 200px;
  height: 150px;
  overflow: hidden;
  border-radius: 4px;
}

.hotel-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hotel-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.hotel-name {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: 600;
}

.hotel-location {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
  margin-bottom: 10px;
  font-size: 14px;
}

.hotel-rating {
  margin-bottom: 15px;
}

.hotel-latest-review {
  margin-bottom: 15px;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

.review-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #606266;
}

.review-content {
  font-size: 14px;
}

.review-text {
  margin-bottom: 5px;
  color: #606266;
  line-height: 1.5;
}

.review-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.hotel-actions {
  margin-top: auto;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.admin-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  width: 100%;
}

.pagination-box {
  padding-top: 16px;
  display: flex;
  justify-content: right;
}

@media (max-width: 768px) {
  .hotel-layout {
    flex-direction: column;
  }
  
  .hotel-image {
    width: 100%;
    height: 200px;
  }
}
</style>
